const {sendErr} = require("./getSendResult")
const {pathToRegexp} = require("path-to-regexp");
const jwt = require("./jwt")
const needToKenApi = [
    {path:"/api/student/login"},
    {path:"/api/student/register"},
    {path:"/api/student/find"},
    {path:"/api/admin/login"},
    {path:"/upload/:id"}
]
// 用于解析token
module.exports = (req,res,next) =>{
    const apis = needToKenApi.filter(api => {
        const reg = pathToRegexp(api.path)
        return reg.test(req.path)
    })
    if(apis.length !== 0){
        next()
        return
    }
    const result = jwt.verify(req)
    if(result){
        req.user = result;
        next()
    }else{
        
        handlerNonToken(req,res,next)
    }
}





// 处理没有认证的情况
function handlerNonToken(req,res,next){
    res.status(406).send(sendErr("you dont have any token to access the api",406))
}